package cn.dengta.webapp.risk.util;

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import javax.annotation.Nonnull;

import cn.dengta.common.model.Messager;
import cn.dengta.common.util.BaseHttpUtil;
import cn.dengta.context.model.AppContext;
import cn.dengta.context.model.WesKit;
import cn.dengta.webapp.risk.bean.RiskConstants;
import cn.dengta.webapp.risk.bean.RiskType;
import cn.dengta.webapp.risk.vo.SmRiskVO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.http.HttpMethod;

@Slf4j
public class SmHttpUtil extends BaseHttpUtil {

	/**
	 * 只有接口调用成功时，才会返回 status == "OK" 以及对应的数据实体
	 */
	@Nonnull
	public static Messager<SmRiskVO> post(WesKit wesKit, RiskType type, String requestBody) {
		final String url = wesKit.isInterior() ? type.getUrl_cn() : type.getUrl();
		//final String url = type.getUrl_cn(); // 服务器已迁移到 香港 直接走国内地址
		HttpRequest request = requestBuilder(HttpMethod.POST, url, requestBody, true)
				.timeout(type.getTimeout())
				.build();

		String body = null;
		Exception ex = null;
		try {
			HttpResponse<String> response = sendWithRetryWhenGoawayReceived(httpClient, request, responseBodyHandler);
			body = response.body();

			SmRiskVO vo = JSON.parseObject(body, SmRiskVO.class);

			body = StringEscapeUtils.unescapeJson(body); // 将 Unicode 编码字符 转为 常规文本

			if (vo != null && vo.getCode() == RiskConstants.SUCCESS_CODE) {
				return Messager.hideData(vo);
			}

			final String msg = vo == null ? null : vo.getMessage();
			return Messager.error(msg);
		} catch (Exception e) {
			ex = e;
			return Messager.error("风控接口调用失败！");
		} finally {
			if (ex == null) {
				log.info("【数美风控】接口请求地址：{}，请求参数：{}，返回数据：{}", url, requestBody, body);
			} else {
				log.error("【数美风控】接口请求失败，地址：{}，请求参数：{}", url, requestBody, ex);
			}
		}

	}

}
